<template>
  <!-- 最外层的包围  -->
  <div class="chat">
	<!-- 语音视频 通话组件 -->
	<TUICallKit></TUICallKit> 
	<!-- 外层包围 -->
    <div :class="['tui-chat', !isPC && 'tui-chat-h5']">
	  <!-- 如果没有有 当前对话ID 显示默认沟槽 -->
      <div
        v-if="!currentConversationID"
        :class="['tui-chat-default', !isPC && 'tui-chat-h5-default']"
      >
	    <!-- 默认插槽标签  -->
        <slot />
      </div>
	  <!-- 如果有 当前对话ID 显示 沟槽 -->
      <div
        v-if="currentConversationID"
        :class="['tui-chat', !isPC && 'tui-chat-h5']"
      >
	    <!-- 消息头 信息展示  || 更新聊天头信息 只是针对 c2c 有效 ， 显示对方名字 或者 对方正在输入中  其实这个组件 修改的是全局变量 title -->
        <ChatHeader
          :class="[
            'tui-chat-header',
            !isPC && 'tui-chat-H5-header',
            isUniFrameWork && 'tui-chat-uniapp-header',
          ]"
          :isGroup="isGroup"
          :headerExtensionList="headerExtensionList"
          @closeChat="closeChat"
          @openGroupManagement="handleGroup"
        />
		<!-- 长按 转发 信息展示  -->
        <Forward @toggleMultipleSelectMode="toggleMultipleSelectMode" />
		<!-- 消息列表 信息展示  -->
        <MessageList
          ref="messageListRef"
          :class="['tui-chat-message-list', !isPC && 'tui-chat-h5-message-list']"
          :isGroup="isGroup"
          :groupID="groupID"
          :isNotInGroup="isNotInGroup"
          :isMultipleSelectMode="isMultipleSelectMode"
          @handleEditor="handleEditor"
          @closeInputToolBar="() => changeToolbarDisplayType('none')"
          @toggleMultipleSelectMode="toggleMultipleSelectMode"
        />
		<!-- 判断是否在 群内消息 离开群的消息 -->
        <div
          v-if="isNotInGroup"
          :class="{
            'tui-chat-leave-group': true,
            'tui-chat-leave-group-mobile': isMobile,
          }"
        >
          {{ leaveGroupReasonText }}
        </div>
		<!-- 多选 控制面板 信息展示  -->
        <MultipleSelectPanel
          v-else-if="isMultipleSelectMode"
          @oneByOneForwardMessage="oneByOneForwardMessage"
          @mergeForwardMessage="mergeForwardMessage"
          @toggleMultipleSelectMode="toggleMultipleSelectMode"
        />
        <template v-else>
		  <!-- 信息输入 工具栏  -->
          <MessageInputToolbar
            v-if="isInputToolbarShow"
            :class="[
              'tui-chat-message-input-toolbar',
              !isPC && 'tui-chat-h5-message-input-toolbar',
              isUniFrameWork && 'tui-chat-uni-message-input-toolbar'
            ]"
            :displayType="inputToolbarDisplayType"
            @insertEmoji="insertEmoji"
            @changeToolbarDisplayType="changeToolbarDisplayType"
            @scrollToLatestMessage="scrollToLatestMessage"
          />
		  <!-- 信息输入框  -->
          <MessageInput
            ref="messageInputRef"
            :class="[
              'tui-chat-message-input',
              !isPC && 'tui-chat-h5-message-input',
              isUniFrameWork && 'tui-chat-uni-message-input',
              isWeChat && 'tui-chat-wx-message-input',
            ]"
            :enableAt="featureConfig.InputMention"
            :isMuted="false"
            :muteText="TUITranslateService.t('TUIChat.您已被管理员禁言')"
            :placeholder="TUITranslateService.t('TUIChat.请输入消息')"
            :inputToolbarDisplayType="inputToolbarDisplayType"
            @changeToolbarDisplayType="changeToolbarDisplayType"
          />
        </template>
      </div>
      <!-- Group Management  快捷群管理 只有群 web 模式下 -->
      <div
        v-if="!isNotInGroup && !isApp && isUniFrameWork && isGroup && headerExtensionList.length > 0"
        class="group-profile"
        @click="handleGroup"
      >
        {{ headerExtensionList[0].text }}
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
// vue2 支持 vue3 的语法支持 
import { ref, onMounted, onUnmounted, computed } from '/TUIKit/adapter-vue';
// SDK 引擎数据调用
import TUIChatEngine, {
  TUITranslateService,
  TUIConversationService,
  TUIStore,
  StoreName,
  IMessageModel,
  IConversationModel,
} from '@tencentcloud/chat-uikit-engine';
// UI 核心组件
import TUICore, { TUIConstants, ExtensionInfo } from '@tencentcloud/tui-core';
// 引入 语音通话
import { TUICallKit } from "@tencentcloud/call-uikit-vue";
// 顶部信息
import ChatHeader from './chat-header/index.vue';
// 消息列表
import MessageList from './message-list/index.vue';
// 消息输入
import MessageInput from './message-input/index.vue';
// 多选控制面板
import MultipleSelectPanel from './mulitple-select-panel/index.vue';
// 转发功能
import Forward from './forward/index.vue';
// 输入工具条
import MessageInputToolbar from './message-input-toolbar/index.vue';
// 业务环境控制
import { isPC, isWeChat, isUniFrameWork, isMobile, isApp } from '/TUIKit/utils/env';
// 工具栏 显示类型
import { ToolbarDisplayType } from '../../interface';
// 配置文件
import TUIChatConfig from './config';

// 特有的 uniapp 启动聊天 开始
// @Start uniapp use Chat only
import { onLoad, onUnload } from '@dcloudio/uni-app';
// 初始化聊天 退出
import { initChat, logout } from './entry-chat-only.ts';

// 声音 开关
const switchAudio = ref();

// 加载时刻 自动初始化 聊天
onLoad((options) => {
  initChat(options);
  if(uni.getStorageInfoSync('switchAudio')){
	  switchAudio.value = uni.getStorageInfoSync('switchAudio')
  }
});

// 当关闭当前页面时候 执行退出
onUnload(() => {
  // Whether logout is decided by yourself  when the page is unloaded. The default is false.
  logout(false).then(() => {
    // Handle success result from promise.then when you set true.
  }).catch(() => {
    // handle error
  });
});
// @End uniapp use Chat only
// 特有的 uniapp 启动聊天 结束

// 定义 事件发射 发射给父组件的方法 会激活父组件 的这个方法的调用  好处是 不用当前模组中实现业务逻辑 
const emits = defineEmits(['closeChat']);

// 定义群ID
const groupID = ref(undefined);
// 定义是否为群
const isGroup = ref(false);
// 定义是否不为群
const isNotInGroup = ref(false);
// 定义 不在群内原因
const notInGroupReason = ref<number>();
// 定义当前会话ID
const currentConversationID = ref();
// 定义 是否多选模式
const isMultipleSelectMode = ref(false);
// 输入工具条 显示类型
const inputToolbarDisplayType = ref<ToolbarDisplayType>('none');
// 消息输入
const messageInputRef = ref();
// 消息列表
const messageListRef = ref<InstanceType<typeof MessageList>>();
// 顶部异常信息
const headerExtensionList = ref<ExtensionInfo[]>([]);
// 特殊配置 
const featureConfig = TUIChatConfig.getFeatureConfig();

// 加载时刻的配置  监听
onMounted(() => {
  TUIStore.watch(StoreName.CONV, {
    currentConversation: onCurrentConversationUpdate,
  });
});

// 去加载时刻 配置  去监听
onUnmounted(() => {
  TUIStore.unwatch(StoreName.CONV, {
    currentConversation: onCurrentConversationUpdate,
  });
  reset();
});

// 是否展示输入框 工具条
const isInputToolbarShow = computed<boolean>(() => {
  return isUniFrameWork ? inputToolbarDisplayType.value !== 'none' : true;
});

// 默认 群外 提示语句
const leaveGroupReasonText = computed<string>(() => {
  let text = '';
  switch (notInGroupReason.value) {
    case 4:
      text = TUITranslateService.t('TUIChat.您已被管理员移出群聊');
      break;
    case 5:
      text = TUITranslateService.t('TUIChat.该群聊已被解散');
      break;
    case 8:
      text = TUITranslateService.t('TUIChat.您已退出该群聊');
      break;
    default:
      text = TUITranslateService.t('TUIChat.您已退出该群聊');
      break;
  }
  return text;
});

// 重置 方法
const reset = () => {
  TUIConversationService.switchConversation('');
};

// 关闭聊天
const closeChat = (conversationID: string) => {
  emits('closeChat', conversationID);
  reset();
};

// 插入 表情包
const insertEmoji = (emojiObj: object) => {
  messageInputRef.value?.insertEmoji(emojiObj);
};

// 编辑处理 
const handleEditor = (message: IMessageModel, type: string) => {
  if (!message || !type) return;
  switch (type) {
	  // 引用
    case 'reference':
      // todo
      break;
	  // 回复
    case 'reply':
      // todo
      break;
	  // 重新编辑
    case 'reedit':
      if (message?.payload?.text) {
        messageInputRef?.value?.reEdit(message?.payload?.text);
      }
      break;
    default:
      break;
  }
};

// 处理群组信息
const handleGroup = () => {
  headerExtensionList.value[0].listener.onClicked({ groupID: groupID.value });
};

// 修改工具条展示形式
function changeToolbarDisplayType(type: ToolbarDisplayType) {
  inputToolbarDisplayType.value = inputToolbarDisplayType.value === type ? 'none' : type;
  if (inputToolbarDisplayType.value !== 'none' && isUniFrameWork) {
    uni.$emit('scroll-to-bottom');
  }
}

// 滚动到 最后一条 消息
function scrollToLatestMessage() {
  messageListRef.value?.scrollToLatestMessage();
}

// 折叠多选模式
function toggleMultipleSelectMode(visible?: boolean) {
  isMultipleSelectMode.value = visible === undefined ? !isMultipleSelectMode.value : visible;
}

// 合并转发信息
function mergeForwardMessage() {
  messageListRef.value?.mergeForwardMessage();
}

// 逐一转发
function oneByOneForwardMessage() {
  messageListRef.value?.oneByOneForwardMessage();
}

// 更新不在群内的 用户信息
function updateUIUserNotInGroup(conversation: IConversationModel) {
  if (conversation?.operationType > 0) {
    headerExtensionList.value = [];
    isNotInGroup.value = true;
    /**
     * 4 - be removed from the group
     * 5 - group is dismissed
     * 8 - quit group
     */
    notInGroupReason.value = conversation?.operationType;
  } else {
    isNotInGroup.value = false;
    notInGroupReason.value = undefined;
  }
}

// 当前对话更新升级
function onCurrentConversationUpdate(conversation: IConversationModel) {
  updateUIUserNotInGroup(conversation);
  // return when currentConversation is null
  if (!conversation) {
    return;
  }
  // return when currentConversationID.value is the same as conversation.conversationID.
  if (currentConversationID.value === conversation?.conversationID) {
    return;
  }

  isGroup.value = false;
  let conversationType = TUIChatEngine.TYPES.CONV_C2C;
  const conversationID = conversation.conversationID;
  if (conversationID.startsWith(TUIChatEngine.TYPES.CONV_GROUP)) {
    conversationType = TUIChatEngine.TYPES.CONV_GROUP;
    isGroup.value = true;
    groupID.value = conversationID.replace(TUIChatEngine.TYPES.CONV_GROUP, '');
  }

  headerExtensionList.value = [];
  isMultipleSelectMode.value = false;
  // Initialize chatType
  TUIChatConfig.setChatType(conversationType);
  // While converstaion change success, notify callkit and roomkit、or other components.
  TUICore.notifyEvent(TUIConstants.TUIChat.EVENT.CHAT_STATE_CHANGED, TUIConstants.TUIChat.EVENT_SUB_KEY.CHAT_OPENED, { groupID: groupID.value });
  // The TUICustomerServicePlugin plugin determines if the current conversation is a customer service conversation, then sets chatType and activates the conversation.
  TUICore.callService({
    serviceName: TUIConstants.TUICustomerServicePlugin.SERVICE.NAME,
    method: TUIConstants.TUICustomerServicePlugin.SERVICE.METHOD.ACTIVE_CONVERSATION,
    params: { conversationID: conversationID },
  });
  // When open chat in room, close main chat ui and reset theme.
  if (TUIChatConfig.getChatType() === TUIConstants.TUIChat.TYPE.ROOM) {
    if (TUIChatConfig.getFeatureConfig(TUIConstants.TUIChat.FEATURE.InputVoice) === true) {
      TUIChatConfig.setTheme('light');
      currentConversationID.value = '';
      return;
    }
  }
  // Get chat header extensions
  if (TUIChatConfig.getChatType() === TUIConstants.TUIChat.TYPE.GROUP) {
    headerExtensionList.value = TUICore.getExtensionList(TUIConstants.TUIChat.EXTENSION.CHAT_HEADER.EXT_ID);
  }
  TUIStore.update(StoreName.CUSTOM, 'activeConversation', conversationID);
  currentConversationID.value = conversationID;
}
</script>

<style scoped lang="scss" src="./style/index.scss"></style>
